package com.yanxu.atomic;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/29-2025
 * @Description: 使用 AtomicReference 实现自旋锁
 */
public class SpinLockWithAtomicReference {
    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //上锁
    public void lock(){
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    //解锁
    public void unlock(){
        Thread thread = Thread.currentThread();
        boolean b = atomicReference.compareAndSet(thread, null);
        if (!b){
            System.out.println("你都没有持有锁，你解锁个毛线啊!!!");
        }
    }
}